import traceback

from django.db import models
import pymongo
from pymongo.errors import PyMongoError
from pymongo.cursor import Cursor

# 全局设置，如访问的数据库
DB = "employee_info_db"


# Create your models here.
def insert_data(coll: str, data: dict) -> bool:
    try:
        mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
        database = mongo_client.get_database(name=DB)
        collection = database.get_collection(name=coll)
        collection.insert(data)
        mongo_client.close()
        return True
    except PyMongoError as mon_ex:
        print(repr(mon_ex))
        traceback.print_exc()
        return False


def query_data(coll: str, filter: dict) -> Cursor:
    try:
        mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
        database = mongo_client.get_database(name=DB)
        collection = database.get_collection(name=coll)
        result = collection.find(filter)
        mongo_client.close()
        return result
    except PyMongoError as mon_ex:
        print(repr(mon_ex))
        traceback.print_exc()


def update_data(coll: str, filter: dict, data: dict) -> bool:
    try:
        mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
        database = mongo_client.get_database(name=DB)
        collection = database.get_collection(name=coll)
        docu = {"$set": data}
        collection.update(filter, docu)
        return True
    except PyMongoError as mon_ex:
        print(repr(mon_ex))
        traceback.print_exc()
        return False


def delete_data(coll: str, filter: dict) -> bool:
    try:
        mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
        database = mongo_client.get_database(name=DB)
        collection = database.get_collection(name=coll)
        if collection.delete_one(filter).deleted_count == 1:
            return True
        else:
            return False
    except PyMongoError as mon_ex:
        print(repr(mon_ex))
        traceback.print_exc()
        return False
